﻿@model EquipmentStockListModel
@using Nop.Core.Domain.XJ
@using Nop.Services.Security

@Html.ValidationSummary(false)

@{
    Layout = "~/Administration/Views/Shared/_AdminPopupLayout.cshtml";

    //page title
    ViewBag.Title = "使用中明细";

    var permissionService = EngineContext.Current.Resolve<IPermissionService>();
    var canManageEquipmentsEdit = permissionService.Authorize(StandardPermissionProvider.ManageEquipmentsEdit);
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="content-header clearfix">
        <h1 class="pull-left">
            使用中明细
        </h1>
        <div class="pull-right">
            @if (canManageEquipmentsEdit)
            {
                <a id="delete-selected" href="javascript:;" class="btn bg-red">
                    <i class="fa fa-trash-o"></i>
                    删除选中
                </a>
                <a href="javascript:generate();" class="btn bg-blue">
                    <i class="fa fa-sliders"></i>
                    批量生成
                </a>
                <a href="javascript:add();" class="btn bg-blue">
                    <i class="fa fa-plus-square"></i>
                    @T("Admin.Common.AddNew")
                </a>
            }
        </div>
    </div>
    <div class="content" style="padding-top:0;">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <div class="col-md-2 col-search">
                                        <div class="label-wrapper"><label class="control-label" for="SearchPlaceId" title="">巡检点</label></div>
                                        <div class="col-content">
                                            @Html.NopDropDownListFor(model => model.SearchPlaceId, Model.AvailablePlaces)
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-search">
                                        <div class="label-wrapper"><label class="control-label" for="SearchLocation" title="">具体位置</label></div>
                                        <div class="col-content">
                                            @Html.NopEditorFor(model => model.SearchLocation)
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-search">
                                        <div class="label-wrapper"><label class="control-label" for="SearchState" title="">状态</label></div>
                                        <div class="col-content">
                                            @Html.NopDropDownListFor(model => model.SearchState, Model.AvailableStates)
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <button type="button" id="btnSearchLogs" class="btn btn-primary"><i class="fa fa-search"></i>@T("Admin.Common.Search")</button>
                                        <button type="button" id="btnCancelLogs" class="btn btn-default"><i class="fa fa-refresh"></i>重置</button>
                                        <input id="btnRefreshLogs" style="display: none" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="panel panel-default">
                    <div class="panel-body">
                        @{
                            var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
                            var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;
                        }


                        <div id="logs-grid"></div>

                        <script>


                            var selectedIds = [];

                            $(document).ready(function () {
                                var columns = [
                                    {
                                        field: "Id",
                                        headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                        template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                        width: 50
                                    },
                                    {
                                        field: "Name",
                                        title: "名称",
                                        width: 300,
                                        headerAttributes: { style: "text-align:center" },
                                    }, {
                                        field: "Manufacturer",
                                        title: "品牌",
                                        width: 200,
                                        headerAttributes: { style: "text-align:center" },
                                    }, {
                                        field: "Specification",
                                        title: "规格型号",
                                        width: 300,
                                        headerAttributes: { style: "text-align:center" },
                                    }, {
                                        field: "PlaceName",
                                        title: "巡检点",
                                        width: 150,
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                    }, {
                                        field: "Location",
                                        title: "使用区域具体位置",
                                        width: 400,
                                        headerAttributes: { style: "text-align:center" },
                                    }, {
                                        field: "StartOn",
                                        title: "开始时间",
                                        width: 100,
                                        type: "date",
                                        format: "{0:yyyy/MM/dd}",
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                    }, {
                                        field: "EndOn",
                                        title: "结束时间",
                                        width: 100,
                                        type: "date",
                                        format: "{0:yyyy/MM/dd}",
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                    }, {
                                        field: "Days",
                                        title: "使用寿命",
                                        width: 100,
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:right" },
                                        template: '<span >#=Days#天</span>'
                                    }, {
                                        field: "StateName",
                                        title: "状态",
                                        width: 100,
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                    }
                                ];
                                if (@(canManageEquipmentsEdit?1:0)== 1) {
                                    columns.push({
                                        field: "Id",
                                        title: "操作",
                                        width: 100,
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                        template: '#if(State==@((int)StockStateEnum.正常)) {# <i class="fa fabtn fa-pencil" title="编辑" onclick="javascript: OpenWindow(\'@(Url.Action("EditPopup", "EquipmentStock"))/#=Id#?btnId=btnRefreshLogs\', 600, 550, true);return false;"></i> #} if(State==@((int)StockStateEnum.正常)) {# <i class="fa fa-stop" onclick="javascript:stop(#=Id#);" title="停止使用"></i> #} else {# <i class="fa fa-play" onclick="javascript:start(#=Id#);" title="恢复使用"></i> #} #<i class="fa fabtn fa-trash" title="删除" onclick="javascript: delStock(#=Id#);"></i>'
                                    });
                                }
                                $("#logs-grid").kendoGrid({
                                    dataSource: {
                                        type: "json",
                                        transport: {
                                            read: {
                                                url: "@Html.Raw(Url.Action("List", "EquipmentStock"))",
                                                type: "POST",
                                                dataType: "json",
                                                data: additionalData
                                            }
                                        },
                                        schema: {
                                            data: "Data",
                                            total: "Total",
                                            errors: "Errors",
                                            model: {
                                                id: "Id",
                                                fields: {
                                                    PlaceName: { editable: false, type: "string" },
                                                    Name: { editable: false, type: "string" },
                                                    Manufacturer: { editable: false, type: "string" },
                                                    Specification: { editable: false, type: "string" },
                                                    Location: { editable: false, type: "string" },
                                                    StartOn: { editable: false, type: "date" },
                                                    EndOn: { editable: false, type: "date" },
                                                    Price: { editable: true, type: "number" },
                                                    Amount: { editable: true, type: "number" },
                                                    Id: { editable: false, type: "number" }
                                                }
                                            }
                                        },
                                        requestEnd: function(e) {
                                            if (e.type == "update") {
                                                this.read();
                                            }
                                        },
                                        error: function(e) {
                                            display_kendoui_grid_error(e);
                                            // Cancel the changes
                                            this.cancelChanges();
                                        },
                                        pageSize: @(defaultGridPageSize),
                                        serverPaging: true,
                                        serverFiltering: true,
                                        serverSorting: true
                                    },
                                    pageable: {
                                        refresh: true,
                                        pageSizes: [@(gridPageSizes)],
                                        @Html.Partial("_GridPagerMessages")
                                    },
                                    editable: {
                                        confirmation: "@T("Admin.Common.DeleteConfirmation")",
                                        mode: "inline"
                                    },
                                    scrollable: false,
                                    dataBound: onDataBound,
                                    columns: columns,
                                });
                                $('#btnSearchLogs').click(function () {
                                    //refresh grid
                                    var grid = $("#logs-grid").data('kendoGrid');
                                    grid.dataSource.read();

                                    //return false to don't reload a page
                                    return false;
                                });
                                $('#btnRefreshLogs').click(function () {
                                    //refresh grid
                                    var grid = $("#logs-grid").data('kendoGrid');
                                    grid.dataSource.read();
                                    // 刷新设施设备列表
                                    try {window.opener.document.getElementById('@(ViewBag.btnId)').click();}
                                    catch (e){}
                                    //return false to don't reload a page
                                    return false;
                                });
                                //cancel button
                                $('#btnCancelLogs').click(function () {
                                    //cancel
                                    var grid = $("#logs-grid").data('kendoGrid');
                                    $('#@Html.FieldIdFor(model => model.SearchPlaceId)').val('0');
                                    $('#@Html.FieldIdFor(model => model.SearchState)').val('0');
                                    $('#@Html.FieldIdFor(model => model.SearchLocation)').val('');
                                    grid.dataSource.page(1); //new search. Set page size to 1
                                    //grid.dataSource.read(); we already loaded the grid above using "page" function

                                    return false;
                                });

                                $("#@Html.FieldIdFor(model => model.SearchLocation)").keydown(function(event) {
                                    if (event.keyCode == 13) {
                                        $("#search-categories").click();
                                        return false;
                                    }
                                });

        //"delete selected" button
        $('#delete-selected').click(function(e) {
            e.preventDefault();

            var postData = {
                selectedIds: selectedIds
            };
            addAntiForgeryToken(postData);

            $.ajax({
                cache: false,
                type: "POST",
                url: "@(Url.Action("DeleteSelected", "EquipmentStock"))",
                data: postData,
                dataType: 'json',
                success: function (data) {
                    if (data.Result) {
                        //refresh grid
                        $('#btnRefreshLogs').click();
                        //clear selected checkboxes
                        $('.checkboxGroups').attr('checked', false).change();
                        selectedIds = [];
                    }
                    else {
                        alert(data.Msg);
                    }
                    return false;
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(thrownError);
                },
                traditional: true
            });
            return false;
        });

                                $('#mastercheckbox').click(function () {
                                    $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                                });

                                //wire up checkboxes.
                                $('#logs-grid').on('change', 'input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]', function (e) {
                                    var $check = $(this);
                                    if ($check.is(":checked") == true) {
                                        var checked = jQuery.inArray($check.val(), selectedIds);
                                        if (checked == -1) {
                                            //add id to selectedIds.
                                            selectedIds.push($check.val());
                                        }
                                    } else {
                                        var checked = jQuery.inArray($check.val(), selectedIds);
                                        if (checked > -1) {
                                            //remove id from selectedIds.
                                            selectedIds = $.grep(selectedIds, function (item, index) {
                                                return item != $check.val();
                                            });
                                        }
                                    }
                                    updateMasterCheckbox();
                                });
                            });

                            function onDataBound(e) {
                                $('#logs-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').each(function () {
                                    var currentId = $(this).val();
                                    var checked = jQuery.inArray(currentId, selectedIds);
                                    //set checked based on if current checkbox's value is in selectedIds.
                                    $(this).attr('checked', checked > -1);
                                });

                                updateMasterCheckbox();
                            }

                            function updateMasterCheckbox() {
                                var numChkBoxes = $('#logs-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').length;
                                var numChkBoxesChecked = $('#logs-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]:checked').length;
                                $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                            }
                            function additionalData() {
                                var data = {
                                    SearchPlaceId: $('#@Html.FieldIdFor(model => model.SearchPlaceId)').val(),
                                    SearchEquipmentId:@Model.SearchEquipmentId,
                                    SearchLocation: $('#@Html.FieldIdFor(model => model.SearchLocation)').val(),
                                    SearchState: $('#@Html.FieldIdFor(model => model.SearchState)').val(),
                                };
                                addAntiForgeryToken(data);
                                return data;
                            }
                            function stop(id) {
                            if (confirm('@T("Admin.Common.AreYouSure")')) {
                                var postData = {
                                    id
                                };
                                addAntiForgeryToken(postData);

                                $.ajax({
                                    cache: false,
                                    type: 'POST',
                                    url: '@Url.Action("StockStop", "EquipmentStock")',
                                    data: postData,
                                    dataType: 'json',
                                    success: function (data) {
                                        //refresh grid
                                        var grid = $("#logs-grid").data('kendoGrid');
                                        grid.dataSource.read();
                                        try {window.opener.document.getElementById('@(ViewBag.btnId)').click();}
                                        catch (e){}
                                        return false;
                                    },
                                    error: function(xhr, ajaxOptions, thrownError) {
                                        alert('Failed to delete');
                                    }
                                });
                            }
                            }
                            function start(id) {
                            if (confirm('@T("Admin.Common.AreYouSure")')) {
                                var postData = {
                                    id
                                };
                                addAntiForgeryToken(postData);

                                $.ajax({
                                    cache: false,
                                    type: 'POST',
                                    url: '@Url.Action("StockStart", "EquipmentStock")',
                                    data: postData,
                                    dataType: 'json',
                                    success: function (data) {
                                        //refresh grid
                                        var grid = $("#logs-grid").data('kendoGrid');
                                        grid.dataSource.read();
                                        try {window.opener.document.getElementById('@(ViewBag.btnId)').click();}
                                        catch (e){}
                                        return false;
                                    },
                                    error: function(xhr, ajaxOptions, thrownError) {
                                        alert('Failed to delete');
                                    }
                                });
                            }
                            }
                            function add() {
                                const eId = @Model.SearchEquipmentId;
                                OpenWindow('@(Url.Action("AddPopup", "EquipmentStock"))?eId=' + eId + '&btnId=btnRefreshLogs', 600, 550, true);
                            }
                            function delStock(id) {
                                if (confirm('@T("Admin.Common.AreYouSure")')) {
                                    var postData = {
                                        id
                                    };
                                    addAntiForgeryToken(postData);

                                    $.ajax({
                                        cache: false,
                                        type: 'POST',
                                        url: '@Url.Action("Delete", "EquipmentStock")',
                                        data: postData,
                                        dataType: 'json',
                                        success: function (data) {
                                            if (data.result) {
                                                //refresh grid
                                                $('#btnRefreshLogs').click();
                                            }
                                            else {
                                                alert(data.msg);
                                            }
                                            return false;
                                        },
                                        error: function(xhr, ajaxOptions, thrownError) {
                                            alert('Failed to delete');
                                        }
                                    });
                                }
                        }
                            function generate() {
                            const id = @Model.SearchEquipmentId;
                            if (id <= 0) return;
                            if (confirm('批量为所有关联巡检点生成一条使用中明细')) {
                                var postData = {
                                    id
                                };
                                addAntiForgeryToken(postData);

                                $.ajax({
                                    cache: false,
                                    type: 'POST',
                                    url: '@Url.Action("StockGenerate", "EquipmentStock")',
                                    data: postData,
                                    dataType: 'json',
                                    success: function (data) {
                                        //refresh grid
                                        var grid = $("#logs-grid").data('kendoGrid');
                                        grid.dataSource.read();
                                        try {window.opener.document.getElementById('@(ViewBag.btnId)').click();}
                                        catch (e){}
                                        return false;
                                    },
                                    error: function(xhr, ajaxOptions, thrownError) {
                                        alert('Failed to generate');
                                    }
                                });
                            }
                            }
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
}